package com.fh.auth;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.CredentialsToPrincipalResolver;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.SimplePrincipal;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;

public class MyReturnMoreInfoCredentialsToPrincipalResolver implements CredentialsToPrincipalResolver {

	private DataSource dataSource;

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public Principal resolvePrincipal(Credentials credentials) {
		final UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) credentials;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String id = null;
		String address = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			conn = dataSource.getConnection();
			String username = usernamePasswordCredentials.getUsername();
			String password = usernamePasswordCredentials.getPassword();
			
			map.put("username", username);
			map.put("password", password);
			
			String sql = " select id,address from tb_sys_user where userName=? and password=? ";
			ps = conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, password);
			rs = ps.executeQuery();
			if (rs != null && rs.next()) {
				id = rs.getString("id");
				address = rs.getString("address");
				map.put("id", id);
				map.put("address", URLEncoder.encode(address, "UTF-8"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (ps != null) {
					ps.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return new SimplePrincipal(id, map);
	}

	public boolean supports(Credentials credentials) {
		return credentials != null && UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass());
	}

}
